package server;

import org.apache.log4j.Logger;
import server.session.UserSession;
import unit.response.ServerMessage;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * @author Yuri Denison
 * @since 04.08.11
 */
public class Communicator {
    private HashMap<Integer, LinkedList<UserSession>> userSessions;
    private Logger log = Logger.getLogger(Communicator.class);

    public Communicator() {
        userSessions = new HashMap<Integer, LinkedList<UserSession>>();
    }

    public void addUserSession(UserSession session) {
        if (userSessions.get(session.getUserId()) == null) {
            userSessions.put(session.getUserId(), new LinkedList<UserSession>());
        }
        userSessions.get(session.getUserId()).add(session);
        log.debug("userSession added: userId = " + session.getUserId());
    }

    public void removeUserSession(UserSession session) {
        userSessions.get(session.getUserId()).remove(session);
        log.debug("userSession removed: userId = " + session.getUserId());
    }

    public boolean send(int receiverId, ServerMessage incomingMessage) {
        return userSessions.containsKey(receiverId) && sendToUserId(receiverId, incomingMessage);
    }

    private boolean sendToUserId(int receiverId, ServerMessage incomingMessage) {
        boolean sent = true;
        for (UserSession session : userSessions.get(receiverId)) {
            incomingMessage.setSession(session.getSession());
            sent = session.send(incomingMessage) && sent;
        }
        log.debug("message sent to Id = " + receiverId);
        return sent;
    }

    public boolean send(int[] contactList, ServerMessage incomingMessage) {
        boolean sent = true;
        for (int receiverId : contactList) {
            if (userSessions.containsKey(receiverId)) {
                sendToUserId(receiverId, incomingMessage);
            } else {
                sent = false;
            }
            log.debug("message sent to Id = " + receiverId);
        }
        return sent;
    }

    public int getSessionNumber(int userID) {
        if (userSessions.containsKey(userID)) {
            return userSessions.get(userID).size();
        } else {
            return 0;
        }
    }
}
